#include "providers/gitee_provider.h"
#include <iostream>
#include <sstream>
#include <cstdlib>

GiteeProvider::GiteeProvider(const std::string& access_token) 
    : access_token_(access_token) {}

bool GiteeProvider::callAPI(const std::string& endpoint, const std::string& method,
                           const std::map<std::string, std::string>& data) {
    // 简化版本：使用 curl 命令行工具
    std::string command = "curl -s -X " + method;
    
    // 添加认证头
    if (!access_token_.empty()) {
        command += " -H \"Authorization: token " + access_token_ + "\"";
    }
    
    // 构建完整 URL
    std::string url = base_url_ + endpoint;
    command += " \"" + url + "\"";
    
    // 添加 POST 数据
    if (method == "POST" && !data.empty()) {
        command += " -d \"";
        for (auto it = data.begin(); it != data.end(); ++it) {
            if (it != data.begin()) command += "&";
            command += it->first + "=" + it->second;
        }
        command += "\"";
    }
    
    std::cout << "🔧 Executing: " << command << std::endl;
    
    int result = system(command.c_str());
    return result == 0;
}

std::string GiteeProvider::buildQueryString(const std::map<std::string, std::string>& params) {
    std::stringstream ss;
    for (auto it = params.begin(); it != params.end(); ++it) {
        if (it != params.begin()) ss << "&";
        ss << it->first << "=" << it->second;
    }
    return ss.str();
}

bool GiteeProvider::createRepository(const std::string& name, const std::string& description, bool is_public) {
    std::cout << "📦 Creating repository: " << name << std::endl;
    
    std::map<std::string, std::string> data = {
        {"name", name},
        {"description", description},
        {"public", is_public ? "true" : "false"}
    };
    
    return callAPI("/user/repos", "POST", data);
}

bool GiteeProvider::createOrganizationRepository(const std::string& org, const std::string& name, const std::string& description) {
    std::cout << "📦 Creating organization repository: " << org << "/" << name << std::endl;
    
    std::map<std::string, std::string> data = {
        {"name", name},
        {"description", description},
        {"public", "true"}
    };
    
    return callAPI("/orgs/" + org + "/repos", "POST", data);
}

bool GiteeProvider::repositoryExists(const std::string& name) {
    return callAPI("/repos/" + name);
}

bool GiteeProvider::organizationRepositoryExists(const std::string& org, const std::string& name) {
    return callAPI("/repos/" + org + "/" + name);
}

bool GiteeProvider::createMirrorRepository(const std::string& name, const std::string& source_url, const std::string& description) {
    std::cout << "🔄 Creating mirror repository: " << name << " <- " << source_url << std::endl;
    
    std::map<std::string, std::string> data = {
        {"name", name},
        {"description", description + " [Mirror of " + source_url + "]"},
        {"public", "true"},
        {"mirror", "true"},
        {"import_from", source_url}
    };
    
    return callAPI("/user/repos", "POST", data);
}

std::string GiteeProvider::extractRepoNameFromUrl(const std::string& url) {
    // 从 URL 中提取仓库名
    // https://github.com/wxWidgets/zlib.git -> zlib
    size_t last_slash = url.find_last_of('/');
    size_t dot_git = url.find_last_of('.');
    if (last_slash != std::string::npos && dot_git != std::string::npos) {
        return url.substr(last_slash + 1, dot_git - last_slash - 1);
    }
    return "";
}

std::string GiteeProvider::extractOrgFromUrl(const std::string& url) {
    // 从 URL 中提取组织名
    // https://github.com/wxWidgets/zlib.git -> wxWidgets
    size_t start = url.find("://");
    if (start == std::string::npos) start = 0;
    else start += 3;
    
    size_t first_slash = url.find('/', start);
    size_t second_slash = url.find('/', first_slash + 1);
    
    if (first_slash != std::string::npos && second_slash != std::string::npos) {
        return url.substr(first_slash + 1, second_slash - first_slash - 1);
    }
    return "";
}
